package org.apache.zookeeper.server.paxos2;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

public abstract class Message {
	
	public static final int START_SYNC = 0;
	public static final int START_SYNC_RESPONSE = 1;
	public static final int FETCH_BLOCKS = 2;
	public static final int FETCH_BLOCKS_RESPONSE = 3;
	
	public abstract void serialize(DataOutputStream out) throws IOException;
	
	public abstract void deserialize(DataInputStream in) throws IOException;
	
	public static void write(Message msg, DataOutputStream out) throws IOException{
		if(msg instanceof StartSync)
			out.writeInt(START_SYNC);
		else if(msg instanceof StartSyncResponse)
			out.writeInt(START_SYNC_RESPONSE);
		else if(msg instanceof FetchBlocks)
			out.writeInt(FETCH_BLOCKS);
		else if(msg instanceof FetchBlocksResponse)
			out.writeInt(FETCH_BLOCKS_RESPONSE);
		else
			throw new IOException("Unknow message "+msg);
		msg.serialize(out);
	}
	
	public static Message read(DataInputStream in) throws IOException{
		Message ret = null;
		int type = in.readInt();
		switch(type){
		case START_SYNC:
			ret = new StartSync();
			break;
		case START_SYNC_RESPONSE:
			ret = new StartSyncResponse();
			break;
		case FETCH_BLOCKS:
			ret = new FetchBlocks();
			break;
		case FETCH_BLOCKS_RESPONSE:
			ret = new FetchBlocksResponse();
			break;
		default:
			throw new IOException("Unknow type "+type);
		}
		ret.deserialize(in);
		return ret;
	}

}
